﻿using SmartDevice.Library.Utils;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO.Ports;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace VoltmeterSimulator
{
    public partial class FormMain : Form
    {
        private readonly SerialPort spCom = new SerialPort();
        private ushort Voltage = 0;

        public FormMain()
        {
            InitializeComponent();
        }

        private void FormMain_Load(object sender, EventArgs e)
        {
            Microsoft.VisualBasic.Devices.Computer pc = new Microsoft.VisualBasic.Devices.Computer();
            foreach (string s in pc.Ports.SerialPortNames)
            {
                this.cmbSPS.Items.Add(s);
            }
            spCom.DataReceived += SpCom_DataReceived;
        }

        private void btnConnect_Click(object sender, EventArgs e)
        {
            int index = this.cmbSPS.SelectedIndex;

            if (index == -1)
            {
                MessageBox.Show("请选择端口", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                return;
            }

            try
            {
                spCom.PortName = this.cmbSPS.Items[index].ToString();
                spCom.Open();

                panel1.Enabled = true;
                btnConnect.Enabled = false;
                btnDisconnect.Enabled = true;
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error:{ex.Message}", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        private void btnDisconnect_Click(object sender, EventArgs e)
        {
            spCom.Close();
            panel1.Enabled = false;
            btnConnect.Enabled = true;
            btnDisconnect.Enabled = false;
        }

        private void SpCom_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            int Count = spCom.BytesToRead;
            byte[] buffer = new byte[Count];
            int bytes = spCom.Read(buffer, 0, Count);

            //写日志
            this.Invoke(new Action(() =>
            {
                var hexstr = ConvertHelper.ByteArrayToHexString(buffer);
                txtLog.Text += $"\r\n[{DateTime.Now:HH:mm:ss}] -> {hexstr}";
            }));

            //响应协议 01 06 01 00 E0 49
            if (bytes == 6 && buffer[0] == 0x01 && buffer[1] == 0x06 && buffer[2] == 0x01 && buffer[3] == 0x00)
            {
                byte[] senddata = new byte[] { 0x01, 0x06, 0x01, 0x02, 0x00, 0x00, 0x00, 0x00 };

                var VoltageBytes = BitConverter.GetBytes(Voltage);
                senddata[4] = VoltageBytes[0];
                senddata[5] = VoltageBytes[1];

                //CRC
                senddata = CRC.CalCRC16a(senddata);

                //发送电压数据
                spCom.Write(senddata, 0, 8);

                //写日志
                this.Invoke(new Action(() =>
                {
                    var hexstr = ConvertHelper.ByteArrayToHexString(senddata);
                    txtLog.Text += $"\r\n[{DateTime.Now:HH:mm:ss}] <- {hexstr}";
                }));
            }
        }

        private void radRadio_CheckedChanged(object sender, EventArgs e)
        {
            this.numVoltage.Enabled = this.btnSet.Enabled = radSet.Checked;
        }

        private void linkClear_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            txtLog.Text = string.Empty;
        }

        private void timer1_Tick(object sender, EventArgs e)
        {
            if (radRandom.Checked)
            {
                Voltage = (ushort)new Random().Next(0, 300);
                this.lblVoltage.Text = $"DC {Voltage:000} V";
            }
        }

        private void btnSet_Click(object sender, EventArgs e)
        {
            Voltage = (ushort)this.numVoltage.Value;
            this.lblVoltage.Text = $"DC {Voltage:000} V";
        }
    }
}
